<template>
	<view class="content">
		<!-- Canvas 用于绘制最终的海报 -->
		<canvas
			:style="{ width: '100vw', height: canvasHeight + 'px', marginLeft: '-999rpx', display: 'flex', alignItems: 'center', justifyContent: 'center' }"
			canvas-id="canvasOne"></canvas>
		<!-- 滑动组件用于展示不同的背景图 -->
		<swiper :style="{ height: canvasHeight + 'px', marginTop: -canvasHeight + 'px' }" @change="swiperChange">
			<swiper-item v-for="(item, index) in bagList" :key="index">
				<view :style="{ position: 'relative', width: '100vw', height: canvasHeight + 'px' }">
					<img :src="item.posterAddress" :style="{ width: '100%', height: '100%' }" alt="" />
				</view>
			</swiper-item>
		</swiper>
		<!-- 提示文本 -->
		<view class='submit-button' @click='savePosterPath'>保存海报</view>
	</view>
</template>

<script>
import { getUserInfo, getqrCode, getQrCodeBag } from '@/api/user.js';
import uploadImage from '@/js_sdk/yushijie-ossutil/ossutil/uploadFile.js';

export default {
	data() {
		return {
			userName: '',
			bagList: [],
			qrImg: '',
			typeId:'',
			screenWidth: uni.getSystemInfoSync().screenWidth,
			currentBackgroundIndex: 0, // 当前选中的背景图索引
		};
	},
	computed: {
		// 计算画布的高度，保持宽高比
		canvasHeight() {
			return this.screenWidth * (690 / 400);
		}
	},
	onLoad(option) {
		this.typeId = option.id
	},
	onShow() {
		this.initData();
	},
	methods: {
		// 初始化数据
		initData() {
			Promise.all([
				getqrCode(),
				getUserInfo(),
				getQrCodeBag({
					pageSize: 99,
					pageNumber: 1,
					state: 1,
					typeId:this.typeId
				})
			]).then((results) => {
				const [qrCodeRes, userRes, bagRes] = results;
				this.qrImg = qrCodeRes.msg;
				this.userName = userRes.data.nickname;
				this.bagList = bagRes.data.records;

				if (this.bagList.length && this.qrImg && this.userName) {
					this.mergeImages(this.bagList[0].posterAddress, 0);
				} else {
					console.error('未能成功加载所有必要数据');
				}
			}).catch(error => {
				console.error('初始化数据失败:', error);
			});
		},
		// 监听滑动事件，切换背景图时合并图像
		swiperChange(e) {
			const currentIndex = e.detail.current;
			this.currentBackgroundIndex = currentIndex;
			this.mergeImages(this.bagList[currentIndex].posterAddress, currentIndex);
		},

		// 合并背景图与二维码
		mergeImages(currentBackground, index = 0, save = false) {
			let context = uni.createCanvasContext('canvasOne');
			context.clearRect(0, 0, this.screenWidth, this.canvasHeight);

			uni.downloadFile({
				url: currentBackground,
				success: (downloadRes) => {
					if (downloadRes.statusCode === 200) {
						const backgroundTempFilePath = downloadRes.tempFilePath;
						context.drawImage(backgroundTempFilePath, 0, 0, this.screenWidth, this.canvasHeight);

						uni.downloadFile({
							url: this.qrImg,
							success: (qrDownloadRes) => {
								if (qrDownloadRes.statusCode === 200) {
									const qrTempFilePath = qrDownloadRes.tempFilePath;

									const qrX = (this.screenWidth - 140) / 2;
									const qrY = this.canvasHeight - 80;
									context.drawImage(qrTempFilePath, qrX, qrY, 65, 65);

									// 绘制文字
									context.setFontSize(14);
									// 计算文字位置
									const textY = this.canvasHeight - 36;
									const nameY = this.canvasHeight - 60;
									context.fillStyle = 'white';
									context.fillText('邀请您加入', (this.screenWidth +10) / 2,
										textY);
									context.fillText(this.userName, (this.screenWidth  +10) /
										2, nameY);

									context.draw(true, () => {
										uni.canvasToTempFilePath({
											destWidth: this.screenWidth*3,
											destHeight: this.canvasHeight*3,
											canvasId: 'canvasOne',
											fileType: 'png', // 修改此行，指定文件类型为 png
											success: (res) => {
												const tempFilePath = res.tempFilePath;
												
												if (save) {
													// 使用OSS上传函数保存海报
													this.uploadImage(tempFilePath, 'posters/', 
														(url) => {
															this.$set(this.bagList[index], 'posterAddress', url);
															this.showTips('海报已更新并保存', 'success');
														}, 
														(error) => {
															console.error('海报上传失败:', error);
															this.showTips('海报上传失败', 'none');
														}
													);
												} else {
													this.$set(this.bagList[index], 'posterAddress', tempFilePath);
													this.showTips('海报已更新', 'none');
												}
											},
											fail: (err) => {
												console.error('海报生成失败:', err);
												this.showTips('海报生成失败', 'none');
											}
										});
									});
								} else {
									console.error('二维码下载失败');
								}
							},
							fail: (err) => {
								console.error('二维码下载失败:', err);
							}
						});
					} else {
						console.error('背景图下载失败');
					}
				},
				fail: (err) => {
					console.error('背景图下载失败:', err);
				}
			});
		},
		// 上传图片到OSS
		uploadImage(filePath, folder, successCallback, errorCallback) {
			uploadImage(filePath, folder, successCallback, errorCallback);
		},
		// 显示提示信息
		showTips(title, icon = 'none') {
			uni.showToast({
				title,
				icon
			});
		},
		savePosterPath() {
			uni.saveImageToPhotosAlbum({
				filePath: this.bagList[this.currentBackgroundIndex].posterAddress,
				success: () => {
					this.$util.Tips({
						title: '保存成功',
						icon: 'success'
					});
				},
				fail: () => {
					this.$util.Tips({
						title: '保存失败'
					});
				}
			});
		}
	}
}
</script>

<style scoped lang="scss">
@import '@/uni.scss';

	.content {
		min-height: 100vh;
		background-color: #fff;
	}

	.submit-button {
		width: 200px;
		height: 40px;
		line-height: 40px;
		background-color: #085CD6;
		border-radius: 40px;
		font-size: 22px;
		color: #fff;
		text-align: center;
		margin: 20px auto;
	}
</style>